package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-07
 * Time: 13:08
 */
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverip, int port) throws IOException {
        //建立tcp连接，此时服务器的accept就会返回
        socket = new Socket(serverip, port);
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerFromSocket = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                //1. 从<键盘>上读取请求
                System.out.println("->");
                String request = scanner.next();
                //2. 把读取的内容构造成请求，发送给服务器
                //发送的带有\n
                printWriter.println(request);
                //刷新缓冲区
                printWriter.flush();
                //3. 从<服务器>读取响应,两个Scanner的读取位置不同
                String response = scannerFromSocket.next();
                //4. 把响应的结果打印到控制台
                System.out.printf("req: %s; resp: %s\n", request, response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
